#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import threading
import os
from PIL import Image, ImageDraw
import pystray
import ctypes


class HealthReminderConfig:
    """配置管理类"""
    REMINDERS = {
        "hourly": {"interval": 60, "message": "每小时提醒：起身活动一下吧！"},
        "stretch": {"interval": 120, "message": "该做拉伸运动了！"},
        "water": {"interval": 30, "message": "快去喝口水吧！"}
    }

    ICON_SIZE = 64
    APP_NAME = "健康助手"
    DEFAULT_MESSAGE = "该休息一下啦！"
    APP_TITLE = "💧 健康提醒"


# 在 ReminderManager 中改进线程管理
class ReminderManager:
    """提醒管理类"""

    def __init__(self):
        self.reminder_thread = None
        self.running = False

    def start_reminder(self, interval, msg):
        """启动提醒线程"""
        self.stop_reminder()  # 先停止当前提醒

        self.running = True

        def reminder():
            try:
                while self.running:
                    time.sleep(interval * 60)
                    if self.running:
                        show_alert(msg)
            except Exception as e:
                print(f"提醒线程发生错误: {e}")

        self.reminder_thread = threading.Thread(target=reminder, daemon=True)
        self.reminder_thread.start()

    def stop_reminder(self):
        """停止提醒线程"""
        self.running = False
        if self.reminder_thread and self.reminder_thread.is_alive():
            self.reminder_thread.join(0.1)

# 初始化提醒管理器
reminder_manager = ReminderManager()


def create_icon(size=64, bg_color=(255, 255, 255), circle_color=(0, 150, 255)):
    """创建托盘图标"""
    img = Image.new('RGB', (size, size), bg_color)
    draw = ImageDraw.Draw(img)

    padding = size // 8  # 计算内边距
    diameter = size - 2 * padding
    draw.ellipse((padding, padding, padding + diameter, padding + diameter),
                 fill=circle_color)
    return img


def show_alert(msg=None):
    """显示提醒消息"""
    message = msg if msg else HealthReminderConfig.DEFAULT_MESSAGE
    print(f"[提醒] {time.strftime('%H:%M')} {message}")
    try:
        ctypes.windll.user32.MessageBoxW(0, message, HealthReminderConfig.APP_TITLE, 0x40)
    except Exception as e:
        print(f"显示提醒时发生错误: {e}")


def start_reminder(icon, interval=1, msg=None):
    """启动定时提醒"""
    reminder_manager.start_reminder(interval, msg if msg else HealthReminderConfig.DEFAULT_MESSAGE)

#退出程序
def quit_app(icon=None, item=None):
    """退出程序"""
    try:
        icon.stop()
        os._exit(0)
    except Exception as e:
        print(f"退出程序时发生错误: {e}")
        os._exit(1)
def create_menu(icon):
    """创建托盘菜单"""
    return pystray.Menu(
        pystray.MenuItem("💧 马上提醒", lambda: show_alert(HealthReminderConfig.REMINDERS["water"]["message"])),
        pystray.MenuItem("⏰ 每小时提醒",
                         lambda: start_reminder(icon, HealthReminderConfig.REMINDERS["hourly"]["interval"],
                                                HealthReminderConfig.REMINDERS["hourly"]["message"])),
        pystray.MenuItem("🧘 拉伸提醒",
                         lambda: start_reminder(icon, HealthReminderConfig.REMINDERS["stretch"]["interval"],
                                                HealthReminderConfig.REMINDERS["stretch"]["message"])),
        pystray.Menu.SEPARATOR,
        pystray.MenuItem("❌ 退出", quit_app)
    )
if __name__ == "__main__":
    try:
        icon = pystray.Icon(HealthReminderConfig.APP_NAME,
                            create_icon(HealthReminderConfig.ICON_SIZE),
                            "健康提醒小助手")
        icon.menu = create_menu(icon)
        start_reminder(icon)
        print("健康助手已启动！右键托盘图标可设置")
        icon.run()
    except Exception as e:
        print(f"程序启动失败: {e}")
        os._exit(1)
